<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Dao\BusinessDao;
use App\Dao\UserAliDao;
use App\Dao\UserWechatDao;
use App\Kernel\Util\UserJwtInstance;
use App\Request\User\Auth\CodeRequest;
use App\Request\User\Auth\LoginRequest;
use App\Request\User\Auth\registerRequest;
use App\Request\User\Auth\retrieveRequest;
use App\Request\User\Auth\retrievePhoneRequest;
use App\Request\User\Auth\shareLoginRequest;
use App\Request\User\Auth\scanLoginRequest;
use App\Service\SMSService;
use App\Service\User\AliService;
use App\Service\User\UserService;
use Hyperf\Guzzle\ClientFactory;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Snowflake\IdGeneratorInterface;

/**
 * 用户鉴权控制器
 *
 * @AutoController()
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Controller\admin
 */
class AuthController extends Controller
{
    /**
     * 用户服务
     *
     * @Inject
     * @var UserService
     */
    private $service;

    /**
     * 短信服务
     *
     * @Inject()
     * @var SMSService
     */
    private $sms;

    /**
     * @Inject()
     *
     * @var IdGeneratorInterface
     */
    private $generator;

    /**
     * @Inject
     * @var UserWechatDao
     */
    private $user_we_chat_dao;

    /**
     * @Inject
     * @var UserAliDao
     */
    private $user_ali_dao;

    /**
     * @Inject
     * @var BusinessDao
     */
    private $business_dao;

    /**
     * @Inject
     * @var AliService
     */
    private $ali_service;

    public function aliAuth()
    {
        $redirect_uri = urlencode('https://scan.sltvip.cn');
        $appId = gConfig('ali_appId');
        $score        = "auth_base";    //auth_user 手动同意 auth_base 静默授权
        $state        = md5("auth_userinfo".time());
        $url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=".$appId."&scope=".$score."&redirect_uri=".$redirect_uri."&state=".$state;

        $this->success($url);
    }

    /**
     * 微信登录
     *
     */
    public function wxLogin()
    {
        $code = (string)$this->request->input('code', 0);

        if( $code ) {
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".gConfig('wx_appId')."&secret=".gConfig('wx_appSecret')."&code=".$code."&grant_type=authorization_code";
            $str = file_get_contents($url);

            $strArr = json_decode($str,true);

            if (isset($strArr['openid']) && !empty($strArr['openid']))
            {
               $user_we_chat =  $this->user_we_chat_dao->fired(['openid' => $strArr['openid']]);
               if( $user_we_chat ) {
                   if( $user_we_chat['user_id'] ) {
                       $userData = $this->service->dao->first($user_we_chat['user_id'],false);
                       if( $userData ) {
                            $return = [
                                'token' => (string)UserJwtInstance::instance()->encode($userData),
                                'openid' => $user_we_chat['openid'],
                            ];
                           $this->success($return);
                       }
                   }
                   $this->success($user_we_chat);
               }
                $user = $this->user_we_chat_dao->insertGetId([
                    'openid' => $strArr['openid'],
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                $result = [
                    'openid' => $strArr['openid'],
                    'id' => $user,
                    'user_id' => 0
                ];
                $this->success($result);
            }
            $this->error();
        } else {
            $this->error();
        }
    }

    /**
     * 支付宝登录
     */
    public function aliLogin()
    {
        $code = (string)$this->request->input('code', 0);

        if( $code ) {

            $result = $this->ali_service->Auth($code);

            if( !empty($result->user_id) ) {

                $user_ali =  $this->user_ali_dao->fired(['userid' => $result->user_id]);

                if( $user_ali ) {
                    if( $user_ali['user_id'] ) {
                        $userData = $this->service->dao->first($user_ali['user_id'],false);
                        if( $userData ) {
                            $return = [
                                'token' => (string)UserJwtInstance::instance()->encode($userData),
                            ];
                            $this->success($return);
                        }
                    }
                    $this->success($user_ali);
                }
                $user = $this->user_ali_dao->insertGetId([
                    'status' => 1,
                    'userid' => $result->user_id,
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                $return = [
                    'userid' => $result->user_id,
                    'id' => $user,
                    'user_id' => 0
                ];
                $this->success($return);

            }else {
                $this->error();
            }

        } else {
            $this->error();
        }
    }

    /**
     * 获取店铺信息
     */
    public function getBusiness()
    {
        $business_id = (int)$this->request->input('business_id', 0);

        $result = $this->business_dao->first(['id'=>$business_id,'status' => 1],['id','name','logo','enable_full_discount']);

        $this->success($result);
    }


    /**
     * 线下扫码
     *
     * @param scanLoginRequest $request
     */
    public function scanLogin(scanLoginRequest $request)
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['code']) && $params['code'] = trim($params['code']);
        $invitation_code = (string)$request->input('invitation_code');

        $result = $this->service->scanLogin($params['phone'], $params['code'], $params['id'], $params['type'], $invitation_code);

        $this->success($result);
    }

    /**
     * 分享登录
     *
     * @param shareLoginRequest $request
     */
    public function shareLogin(shareLoginRequest $request)
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['code']) && $params['code'] = trim($params['code']);
        $invitation_code = (string)$request->input('invitation_code');

        $result = $this->service->shareLogin($params['phone'], $params['code'], $invitation_code);

        $this->success($result);
    }

    /**
     * 登录接口
     *
     * @param registerRequest $request
     */
    public function login(registerRequest $request)
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['login_pwd']) && $params['login_pwd'] = trim($params['login_pwd']);

        $result = $this->service->login($params['phone'], $params['login_pwd']);

        $this->success($result);
    }

    /**
     * 注册接口
     *
     * @param LoginRequest $request
     */
    public function register(LoginRequest $request)
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['login_pwd']) && $params['login_pwd'] = trim($params['login_pwd']);
        isset($params['code']) && $params['code'] = trim($params['code']);
        isset($params['invitation_code']) && $params['invitation_code'] = trim($params['invitation_code']);

        $result = $this->service->register($params['phone'], $params['code'], $params['login_pwd'], $params['invitation_code'] ?? null);

        $this->success($result);
    }

    /**
     * 获取验证码
     *
     * @param CodeRequest $request
     */
    public function get_code(CodeRequest $request)
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);

        $code = substr((string)$this->generator->generate(), -6);
        $this->sms->sendCode($params['phone'], gConfig('ali_templateCode_login', ''), [
            'code' => $code
        ]);

        // TODO 开发环境将验证码报告给前端
        $this->success($code);
    }

    /**
     * 找回密码 - 验证手机
     *
     * @param retrievePhoneRequest $request
     */
    public function retrievePhone ( retrievePhoneRequest $request )
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['code']) && $params['code'] = trim($params['code']);

        $this->service->retrievePhone($params['phone'], $params['code']);

        $this->success();
    }

    /**
     * 找回密码
     *
     * @param retrieveRequest $request
     */
    public function retrieve( retrieveRequest $request )
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['login_pwd']) && $params['login_pwd'] = trim($params['login_pwd']);

        $update = $this->service->dao->retrieve([
            'login_pwd' => password_hash($params['login_pwd'], PASSWORD_DEFAULT )
        ],[
            'phone' => $params['phone']
        ]);

        !$update && $this->error();

        $this->success();
    }

}